package a11_单调栈;

import java.util.Stack;

/**
 * <p>
 * a04_接雨水复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/3/27
 */
public class a04_接雨水复习2 {
    public static void main(String[] args) {
        System.out.println(trap(new int[]{4, 2, 0, 3, 2, 5}));
    }
    //每个柱子能接多少水
    //左边第一个比他大的，右边第一个比他大的
    //
    public static int trap(int[] height) {

        int total = 0;
        Stack<Integer> stack = new Stack<>();
        stack.push(0);

        for (int i = 1; i < height.length; i++) {
            while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
                Integer pop = stack.pop();
                if(!stack.isEmpty()){
                    //计算面积
                    int w = i - stack.peek() - 1;
                    int h = Math.min(height[i],height[stack.peek()]) - height[pop];
                    total = total + (w * h);
                }

            }
            stack.push(i);
        }
        return total;
    }
}
